//
//  ScenicPlayVC.m
//  ImGuider
//
//  Created by llt on 2017/4/19.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "ScenicPlayVC.h"
#import "ScenicPlayCCell.h"
#import "MyPlayProgressView.h"
#import "PlayBar.h"
#import "SDCycleScrollView.h"
#import "GuiderDetailVC.h"
#import "CBAutoScrollLabel.h"
#import "NumberSearchVC.h"
#import "JMHoledView.h"
#import "RecordListDAO.h"
#import "SDPhotoBrowser.h"
#import "IGAvPlayerManager.h"
#import "UserCommentsVC.h"
#import "UserSubmitQustionVC.h"
#import "MyCamera.h"
#import <AVFoundation/AVFoundation.h>
#import "NoticeGuide.h"
@interface ScenicPlayVC () <UICollectionViewDelegate, UICollectionViewDataSource, UIViewControllerTransitioningDelegate,playBarDelegate,SDCycleScrollViewDelegate,NumberSearchVCDelegate,SDPhotoBrowserDelegate>

@property (weak, nonatomic) IBOutlet UIView *BgView;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UIView *menuView;

@property (weak, nonatomic) IBOutlet UIButton *arrowBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgViewBottomSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionViewHeight;
@property (nonatomic, strong) NSMutableArray * menuTagsArray;

//@property (weak, nonatomic) IBOutlet UIView *guiderView;
//
//@property (weak, nonatomic) IBOutlet GuiderIconView *guiderHeaderView;
//
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *guiderViewWidth;
//
//@property (weak, nonatomic) IBOutlet UILabel *guiderNameLabel;
//
////@property (weak, nonatomic) IBOutlet UIButton *mapBtn;
//
//@property (weak, nonatomic) IBOutlet UIView *payView;
//
//@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
//
//@property (weak, nonatomic) IBOutlet StarRateView *starView;
//
//@property (weak, nonatomic) IBOutlet UILabel *visitLabel;
//
//@property (weak, nonatomic) IBOutlet UILabel *scenicPointNumLabel;
//
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *guiViewWidth;
//
//@property (weak, nonatomic) IBOutlet UIButton *guiderBtn;
//
//@property (weak, nonatomic) IBOutlet UILabel *listenNumLabel;
//
//@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
//
//@property (weak, nonatomic) IBOutlet TagView *tagView;
//
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tagViewWidth;
//
//@property (weak, nonatomic) IBOutlet UIButton *buyBtn;
//
//@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
//
//
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toBottomSpace;
//
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *BgViewHeight;


@property (nonatomic, strong)SDCycleScrollView *cycleScrollView;

@property (nonatomic, strong)PlayBar * playBar;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonnull, strong) MyPlayProgressView * progressBar;

@property (nonatomic, strong)NSIndexPath * currenIndexPath;
@property (nonatomic) NSInteger currentIndex;
@property (nonatomic)BOOL isPlay;

@property (nonatomic)BOOL isInView;// 为了改点的太快 出去播放的bug

@property (nonatomic)BOOL isDownload;

@property (nonatomic) BOOL isSuspend;

@end

@implementation ScenicPlayVC


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDownload) name:MCDownloadStartNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDownload) name:MCDownloadStopNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDownload) name:MCDownloadFinishNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessCallback) name:kLoginSuccessNotif object:nil];
    
    


    self.view.backgroundColor = kBGColor;
    
   
   
    self.customBarStyle = UIStatusBarStyleLightContent;
    [self setupCollectionView];
    [self createPlayBar];
    
    [self loadDataSourceWithAlert:self.alert];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [MobClick event:@"7_1_1"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.isInView = YES;
    [MobClick beginLogPageView:@"7"];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (![[IGAvPlayerManager shareManeger].currentURL isEqualToString:self.currentScenicPoint.playpath] && self.currentScenicPoint && ![IGAvPlayerManager shareManeger].isPlay) {
        [IGAvPlayerManager shareManeger].playType = PlayLine;
        [self.playBar playMusicWithIndex:self.currentIndex withIsPlay:NO];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
     self.isInView = NO;
   
}

- (void)setMenuTagsArray:(NSMutableArray *)menuTagsArray {
    
    _menuTagsArray = [NSMutableArray arrayWithArray:menuTagsArray];
    
    if (!(self.lineModel.mapPicArray.count > 0)) {
        [_menuTagsArray removeObject:@(MenuTypeMap)];
    }
    
    if (!self.lineModel.cansearch) {
        [_menuTagsArray removeObject:@(MenuTypeSearch)];
    }
}


- (void)setupMenuView {
    
    self.menuView.backgroundColor =[UIColor whiteColor];// [kThemeDarkColor colorWithAlphaComponent: 0.95];
    CGFloat width = kScreenWidth / self.menuTagsArray.count;
    
    for (int i = 0; i< self.menuTagsArray.count; i ++) {
        
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(i * width, 0, width, 48);
        [self.menuView addSubview:btn];
        
        NSNumber * type = self.menuTagsArray[i];
        
        switch (type.integerValue) {
            case MenuTypeQuestion:
            {
                [btn setImage:[UIImage imageNamed:@"question-grey"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(goQuestion) forControlEvents:UIControlEventTouchUpInside];
            }
                break;
            case MenuTypeComment:
            {
                [btn setImage:[UIImage imageNamed:@"comment-grey"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(goComment) forControlEvents:UIControlEventTouchUpInside];
            }
                break;
            case MenuTypeMap:
            {
                [btn setImage:[UIImage imageNamed:@"map-grey"] forState:UIControlStateNormal];
                [btn setImage:[UIImage imageNamed:@"pic-grey"] forState:UIControlStateSelected];
                self.changeMapBtn = btn;
                [btn addTarget:self action:@selector(changeMapMode:) forControlEvents:UIControlEventTouchUpInside];
            }
                break;
            case MenuTypeCamera:
            {
                [btn setImage:[UIImage imageNamed:@"camera-grey"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(goCamera) forControlEvents:UIControlEventTouchUpInside];
            }
                break;
            case MenuTypeSearch:
            {
                [btn setImage:[UIImage imageNamed:@"search-grey"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(goSearch) forControlEvents:UIControlEventTouchUpInside];
            }
                break;
            default:
                break;
        }
    }
    
    [self noviceGuide];
}

- (void)noviceGuide {
    
    [NoticeGuide showPlayerWithMenu:self.menuTagsArray vc:self];
}


- (IBAction)upOrDownClicked:(UIButton *)sender {
    
    NSString * name;
    BOOL flag = false;
    
    if (sender.selected) {
        name = @"展开";
        self.collectionViewHeight.constant = 140.f;
        self.collectionView.hidden = NO;
        sender.selected = NO;
        
    }else {
        
        name = @"收起";
        self.collectionViewHeight.constant = 0.f;
        flag = YES;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
        if (flag == YES) {
            self.collectionView.hidden = flag;
            sender.selected = flag;
        }
        [sender setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    }];
}



//- (IBAction)searchBtnClicked:(UIButton *)sender {
//
//    NumberSearchVC * searchVC = [[NumberSearchVC alloc] init];
//
//    searchVC.ScenicPointsArray = self.dataSource;
//    searchVC.delegate = self;
//    self.isStraightPlay = YES;
//    RTRootNavigationController * nav = [[RTRootNavigationController alloc] initWithRootViewController:searchVC];
//
//    [self presentViewController:nav animated:YES completion:nil];
//}


//- (IBAction)changeMap:(UIButton *)sender {
//
//    if (!sender.selected) {
//        self.cycleScrollView.imageURLStringsGroup = self.lineModel.mapPicArray;
//        self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFit;
//        self.cycleScrollView.autoScroll = NO;
//        sender.selected = YES;
//    }else {
//        ScenicPoint * scenicPoint = self.dataSource[self.currentIndex];
//         self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
//        self.cycleScrollView.imageURLStringsGroup = scenicPoint.pictureArray;
//        if (scenicPoint.pictureArray.count > 1) {
//            self.cycleScrollView.autoScroll = YES;
//        }else {
//            self.cycleScrollView.autoScroll = NO;
//        }
//
//        sender.selected = NO;
//    }
//}
 
- (void)setIsDownload:(BOOL)isDownload {
    
    if (_isDownload == isDownload) {
        return;
    }
    
    _isDownload = isDownload;
    
    [self.collectionView reloadData];
}

- (void)goQuestion {
    
    UserSubmitQustionVC *questionVC = [[UserSubmitQustionVC alloc] init];
    
    questionVC.lineModel = self.lineModel;
    
    
    [self.navigationController pushViewController:questionVC animated:YES];
}

-(void)goComment {
    
    UserCommentsVC * commentVC = [[UserCommentsVC alloc] init];
    
    if (self.lineModel.hasscore.integerValue >0) {
        
        commentVC.isCanComment = NO;
    }else {
        
        commentVC.isCanComment = YES;
    }
    
    
    
    commentVC.lineID = self.lineModel.lineid;
    [self.navigationController pushViewController:commentVC animated:YES];
}


- (void)changeMapMode:(UIButton *)sender {
    
    if (!sender.selected) {
        self.cycleScrollView.imageURLStringsGroup = self.lineModel.mapPicArray;
        self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFit;
        self.cycleScrollView.autoScroll = NO;
        sender.selected = YES;
    }else {
        ScenicPoint * scenicPoint = self.dataSource[self.currentIndex];
        self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
        self.cycleScrollView.imageURLStringsGroup = scenicPoint.pictureArray;
        if (scenicPoint.pictureArray.count > 1) {
            self.cycleScrollView.autoScroll = YES;
        }else {
            self.cycleScrollView.autoScroll = NO;
        }
        sender.selected = NO;
    }
}

- (void)goCamera {
    if ([self canUserCamera]) {
        
        if ([IGAvPlayerManager shareManeger].isPlay) {
            self.isPlay = YES;
        }
        MyCamera * cameraVC = [[MyCamera alloc] init];
        self.isHideItem = YES;
        [self presentViewController:cameraVC animated:YES completion:nil];
    }else{
        return;
    }
    
}

- (BOOL)canUserCamera {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        
        [IGAlertView alertWithTitle:nil message:MYLocalizedString(@"PUBLIC_CAMERA_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOGPS_ALERT_COMMIT", nil) commit:^{
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            if([[UIApplication sharedApplication] canOpenURL:url]) {
                
                [[UIApplication sharedApplication] openURL:url];
                
            }
        } cancel:nil];
        
        return NO;
    }
    else{
        return YES;
    }
}

- (void)goSearch {
    
    NumberSearchVC * searchVC = [[NumberSearchVC alloc] init];
    
    searchVC.ScenicPointsArray = [NSMutableArray arrayWithArray:self.lineModel.records];
    searchVC.delegate = self;
    self.isHideItem = YES;
    RTRootNavigationController * nav = [[RTRootNavigationController alloc] initWithRootViewController:searchVC];
    [self presentViewController:nav animated:YES completion:nil];
}


- (void)selectSenicPoint:(ScenicPoint *)point {
    
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[self.dataSource  indexOfObject:point] inSection:0];
    
    @weakify(self);
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        @strongify(self);
        if (self.lineModel.bought && self.isInView) {
            
            [self selectCellWithIndex:indexPath.row Immediately:YES];
        }else {
            
            self.cycleScrollView.imageURLStringsGroup = point.pictureArray;
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        }
    });
}
- (void)loadDataSourceWithAlert:(BOOL)alert {
    
    if (self.pageType == 1) {
        
        self.isDownload = YES;
        [self setupData];
        
        @weakify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            @strongify(self);
            [self reloadDownload];
        });
        
        return;
    }
    
    [self setupData];
    
    @weakify(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        @strongify(self);
        [self reloadDownload];
    });
    
    if (!alert) {
        
        return;
    }
    
    if (self.lineModel.inroom) {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:self.lineModel.unionid];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [IGAlertView alertWithTitle:MYLocalizedString(@"PUBLIC_ALERT", nil) message:MYLocalizedString(@"SITEPLAY_AUTO_DOWNLOAD", nil) cancelButtonTitle:nil commitBtn:MYLocalizedString(@"PUBLIC_OK", nil) commit:nil cancel:nil];
            
            [self downloadStart];
        });
        
        return;
    }
    
    [IGAlertView alertWithTitle:MYLocalizedString(@"PUBLIC_ALERT", nil) message:MYLocalizedString(@"PUBLIC_DOWNLOAD_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOWIFI_DOWNLOAD_ALERT_COMMIT", nil) commit:^{
        @strongify(self);
        [self downloadStart];
    } cancel:nil];
}


- (void)reloadDownload {
    
    @weakify(self);
    
    [[DownloadManager sharedManager] downloadStatusForModel:self.lineModel block:^(MCDownloadState state, NSInteger completeCount, NSString *unionid) {
        
        @strongify(self);
        if (![self.lineModel.unionid isEqualToString:unionid]) {
            return ;
        }
        
        if (state == MCDownloadStateNone || state == MCDownloadStateSuspened) {
            self.isDownload = NO;
            
            return ;
        }
        
        if (self.isSuspend) {
            
            return;
        }
        
        self.isDownload = YES;
        
        CGFloat progress = completeCount * 1.0 / self.lineModel.records.count;
        
        self.playBar.downloadState = state;
        self.playBar.downloadProgress = progress;
        
    }];
}



- (void)setupData {
    
    //self.title= self.lineModel.linename;
    if (self.lineModel.records.count > 0) {
        
        self.dataSource = [NSMutableArray arrayWithArray:self.lineModel.records];
        
        self.playBar.lineModel = self.lineModel;
        self.playBar.pointsArray = self.dataSource;
    }
    self.menuTagsArray = [NSMutableArray arrayWithArray:@[@(MenuTypeQuestion),@(MenuTypeComment),@(MenuTypeMap),@(MenuTypeCamera),@(MenuTypeSearch)]];
    
    [self initSelectedCell];
    [self setupMenuView];
    [self.collectionView reloadData];
    
}

- (void)initSelectedCell {
    
    ScenicPoint *model;
    NSIndexPath * indexPath;
    if ( self.dataSource.count > 0 && !self.currentScenicPoint) {
        
        model = self.dataSource[0];
        indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        self.currenIndexPath = indexPath;
        self.currentScenicPoint = model;
        [[IGAvPlayerManager shareManeger] resetPlaySpeed];
        [self.playBar playMusicWithIndex:0 withIsPlay:NO];

    } else {
        
        NSInteger index = [self.dataSource indexOfObject:self.currentScenicPoint];
        
        model = self.currentScenicPoint;
        
        indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        self.currenIndexPath = indexPath;
        self.playBar.playPath = model.playpath;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        });
        
        if (![IGAvPlayerManager shareManeger].isPlay || [IGAvPlayerManager shareManeger].playType != PlayLine) {
            
            [self.playBar playMusicWithIndex:index withIsPlay:NO];
            self.playBar.progressTrackValue = 1.0f;
        }
        
    }
    
    self.currentIndex = indexPath.row;
    self.cycleScrollView.imageURLStringsGroup = model.pictureArray;
    
}

- (IBAction)goGuiderDetailVC:(UIButton *)sender {
    
    [MobClick event:@"7_1_4"];
    for (UIViewController *vc in self.navigationController.viewControllers) {
        
        if ([vc isKindOfClass:[GuiderDetailVC class]]) {
            [self.rt_navigationController removeViewController:vc];
        }
        
        if ([vc isKindOfClass:[BasePlayVC class]] && vc != self) {
            [self.rt_navigationController removeViewController:vc];
        }
    }
    
    GuiderDetailVC * detailVC = [[GuiderDetailVC alloc] init];
    
    detailVC.guiderID = self.lineModel.guideid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


//-(void) configScenicPointNumLableWith:(NSInteger )count {
//
//    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%ld个讲解点",self.lineModel.records.count]];
//
//    // 设置字体和设置字体的范围
//    [string addAttribute:NSFontAttributeName
//                   value:Font(18.0f)
//                    range:NSMakeRange(0, string.length - 4)];
//    // 添加文字颜色
//    [string addAttribute:NSForegroundColorAttributeName
//                    value:kThemeColor
//                    range:NSMakeRange(0, string.length - 4)];
//
//    self.scenicPointNumLabel.attributedText = string;
//}

- (void)setupCollectionView {
    
    CGRect frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 98);
    self.bgViewBottomSpace.constant = 98;
    if (ISiPhoneX) {
        frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 132);
        self.bgViewBottomSpace.constant = 132;
    }
    // 网络加载 --- 创建带标题的图片轮播器
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:frame delegate:nil placeholderImage:[UIImage imageNamed:@"placeholder_squ"]];
    [self.BgView insertSubview:self.cycleScrollView belowSubview:self.collectionView];
    self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.cycleScrollView.delegate = self;
    self.cycleScrollView.currentPageDotColor = kThemeColor; // 自定义分页控件小圆标颜色
    self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"ScenicPlayCCell" bundle:nil] forCellWithReuseIdentifier:@"ScenicPlayCCell"];
    
    UICollectionViewFlowLayout *flayout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat imageHeight = kScreenHeight < 568 ? kScreenWidth * 3 / 4.0f : kScreenWidth;
    if (ISiPhoneX) {
        imageHeight = kScreenWidth /4 *5;
    }
    
    CGFloat height = 140;
    flayout.itemSize = CGSizeMake(height - 25, height);
    flayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    [self.collectionView setCollectionViewLayout:flayout animated:YES];
}


- (void)createPlayBar {
    
    if (!self.playBar) {
        
        self.playBar = [PlayBar shareManeger];
        self.playBar.delegate = self;
        self.playBar.type = 2;
        [self.view addSubview:self.playBar];
        
        [self.playBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).offset(8.0);
            make.leading.equalTo(self.view.mas_leading);
            make.trailing.equalTo(self.view.mas_trailing);
            make.width.mas_equalTo(kScreenWidth);
            make.height.mas_equalTo(90);
        }];
    }
    
    self.playBar.downloadState = MCDownloadStateNone;
}
//- (void)setupNavBar {
//
//    [[[self.navigationController.navigationBar subviews] objectAtIndex:0] setAlpha:0];
//
//    UIBarButtonItem *  backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClicked:)];
//    self.navigationItem.leftBarButtonItem = backItem;
//
//    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"more"] style:UIBarButtonItemStylePlain target:self action:@selector(showMoreMennu)];
//
//    self.navigationItem.rightBarButtonItem = item;
//}

- (void)downloadStart {
    
    [MobClick event:@"7_0_8"];
    
    if (![IGUtil hasLoginOrPresentLogin]) {
        return;
    }

    self.isDownload = YES;
    self.isSuspend = NO;
    
    [[DownloadManager sharedManager] addDownloadWithLineModel:self.lineModel];
}

- (void)downloadSuspend {
    
    self.isDownload = NO;
    self.isSuspend = YES;
    
    [[DownloadManager sharedManager] pauseWithLineModel:self.lineModel];
    
}

- (void)loginSuccessCallback {
    [self loadDataSourceWithAlert:NO];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - playBarDelegate

- (void)changePointTo:(NSInteger)index{
    
    [self changeScenicPointWithIndex:index];
}

#pragma mark-UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}
- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ScenicPlayCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ScenicPlayCCell" forIndexPath:indexPath];
    
    if (self.isDownload) {
        cell.showProgress = YES;
    } else {
        cell.showProgress = NO;
    }
    
    ScenicPoint * scenicPoint = self.dataSource[indexPath.row];
    [cell configDataWith:scenicPoint];
    
    if (indexPath.row == 0  && !self.lineModel.bought) {
        cell.playBtn.hidden = NO;
    }
    cell.select = NO;
    
    if (self.currenIndexPath.row == indexPath.row  && self.lineModel.bought) {
        
        cell.select = YES;
        cell.record = NO;
    }
    
    return cell;
}

- (void)selectCellWithIndex:(NSInteger)index Immediately:(BOOL)isImmediately {
    
    [self changeScenicPointWithIndex:index];
    [self.playBar playMusicWithIndex:index withIsPlay:isImmediately];
}

- (void)changeScenicPointWithIndex:(NSInteger)index {
    
    ScenicPoint * scenicPoint = self.dataSource[index];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    
    if (self.currenIndexPath) {
        ScenicPlayCCell * cell = (ScenicPlayCCell *)[self.collectionView cellForItemAtIndexPath:self.currenIndexPath];
        cell.select = NO;
    }
    ScenicPlayCCell * currenCell = (ScenicPlayCCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    currenCell.select = YES;
    if (scenicPoint.spotpictures && !self.changeMapBtn.selected) {
        
        
        self.cycleScrollView.imageURLStringsGroup = scenicPoint.pictureArray;
        
    }else  if(scenicPoint.map.length > 0){
        
        [self.cycleScrollView selectToIndex:[self.lineModel.mapPicArray indexOfObject:scenicPoint.map]];
    }
    
    
    //    IGLog(@"%@",model.playpath);
    //    [self.playBar playMusicWithPlayPath:model withIsPlay:isImmediately];
    
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    [self.collectionView reloadData];
    self.currenIndexPath = indexPath;
    self.currentIndex = indexPath.row;
    self.currentScenicPoint = scenicPoint;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.currenIndexPath == indexPath || (!self.lineModel.bought && indexPath.row == 0)) {
        return;
    }
    
    ScenicPoint * scenicPoint = self.dataSource[indexPath.row];
    if (self.lineModel.bought) {
        
        if (scenicPoint.canplay && scenicPoint.playpath.length > 0) {
            
            [self selectCellWithIndex:indexPath.row Immediately:YES];
        }
        [MobClick event:@"7_0_3"];
    } else {
        [MobClick event:@"7_1_3"];
        
    }
}

- (void)paySuccessCallback {
    [self loadDataSourceWithAlert:YES];
}
#pragma mark-UICollectionViewDelegateFlowLayout
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                        layout:(UICollectionViewLayout *)collectionViewLayout
        insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(8, 8, 8, 8);//分别为上、左、下、右
}


#pragma mark-SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    if (!self.changeMapBtn.selected) {
        return;
    }
    
    if (self.lineModel.mapPicArray.count > 0) {
        
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        
        browser.sourceImagesContainerView = self.cycleScrollView;
        browser.currentImageIndex = index;
        browser.imageCount = self.lineModel.mapPicArray.count;
        
        browser.delegate = self;
        [browser show];
    }
    
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index {
    
    NSString *picstr = self.lineModel.mapPicArray[index];
    
    return [UIImageView imageFromDiskCacheForKey:picstr];
}
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
    
    NSString *picstr = self.lineModel.mapPicArray[index];
    
    return [NSURL URLWithString:picstr];
}




/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
